import curses
from ai_proxy import query_ai
from config import DEFAULT_BACKEND

def tui(stdscr):
    # 初始化屏幕
    curses.curs_set(1)  # 显示光标
    stdscr.clear()
    height, width = stdscr.getmaxyx()

    # 上窗: 响应显示 (滚动)
    output_win = curses.newwin(height - 3, width, 0, 0)
    output_win.scrollok(True)
    output_win.idlok(True)

    # 下窗: 输入框 (固定底部)
    input_win = curses.newwin(3, width, height - 3, 0)
    input_win.border(0, 0, 0, 0, 0, 0, 0, 0)  # 简单边框
    input_win.addstr(1, 1, "> ")  # 提示符
    input_win.refresh()

    # 响应历史
    history = []

    while True:
        # 获取用户输入 (底部窗)
        input_win.move(1, 3)  # 光标定位
        curses.echo()
        prompt = input_win.getstr(1, 3, width - 4).decode('utf-8').strip()
        if prompt.lower() == 'exit':
            break
        input_win.clear()
        input_win.border()
        input_win.addstr(1, 1, "> ")
        input_win.refresh()

        # 调用 AI 并显示响应 (上窗)
        response = query_ai(prompt, backend=DEFAULT_BACKEND)
        history.append(f"我: {prompt}")
        history.append(f"Ollama: {response}")

        # 重绘上窗
        output_win.clear()
        start_line = max(0, len(history) - (height - 4))  # 支持滚动
        for i, line in enumerate(history[start_line:]):
            output_win.addstr(i, 0, line[:width-1])
        output_win.refresh()

if __name__ == '__main__':
    curses.wrapper(tui)  # 启动 TUI